<?php
namespace app\admin\controller\message;

use app\common\controller\Backend;

class Message extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Message');
    }

    public function index()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 添加城市和学校过滤逻辑
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");
            
            // 如果用户组为2（社区管理用户），只能看到自己城市的数据
            if ($_SESSION['think']['admin']['group_id'] == 2) {
                $city_id = $_SESSION['think']['admin']['city_id'];
            }
            
            // 构建查询对象
            $query = $this->model->where($where)->where('status', 1);
            
            // 添加城市和学校过滤条件
            if ($city_id) {
                $query->where('city_id', $city_id);
            }
            if ($school_id) {
                $query->where('school_id', $school_id);
            }

            $list = $query->order($sort, $order)
                         ->limit($offset, $limit)
                         ->select();
            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
            }
            $total = $query->count();
            
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    // 自动插入session中的城市和学校ID
                    if (isset($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (isset($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                    
                    // 处理接收者ID数组，转换为逗号分隔的字符串
                    if (isset($params['receiver_id']) && is_array($params['receiver_id'])) {
                        $params['receiver_id'] = implode(',', array_filter($params['receiver_id']));
                    }
                    
                    $result = $this->model->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取当前管理员信息并传递ocation_id给视图
        $admin = $this->auth->getUserInfo();
        $ocationId = $admin['ocation_id'] ?? 0;
        $this->view->assign('ocation_id', $ocationId);

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    // 自动插入session中的城市和学校ID（如果记录中没有设置）
                    if (empty($row['city_id']) && isset($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (empty($row['school_id']) && isset($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                    
                    // 处理接收者ID数组，转换为逗号分隔的字符串
                    if (isset($params['receiver_id']) && is_array($params['receiver_id'])) {
                        $params['receiver_id'] = implode(',', array_filter($params['receiver_id']));
                    }
                    
                    $result = $row->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取当前管理员信息并传递ocation_id给视图
        $admin = $this->auth->getUserInfo();
        $ocationId = $admin['ocation_id'] ?? 0;
        $this->view->assign('ocation_id', $ocationId);
        
        // 处理接收者ID，模型的获取器已经自动转换为数组
        $rowData = $row->toArray();
        // receiver_id已经通过模型获取器自动转换为数组，无需再处理
        if (empty($rowData['receiver_id'])) {
            $rowData['receiver_id'] = [];
        }
        
        $this->view->assign("row", $rowData);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
